package cn.gzjp.modules.it.api.web;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.it.api.bean.CommonJson;
import cn.gzjp.modules.it.entity.Member;
import cn.gzjp.modules.it.service.MemberService;
import cn.gzjp.modules.it.service.WxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.exception.WxErrorException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 微信小程序用户接口
 *
 */
@Controller("wxMaUser")
@Api(value = "用户管理", description = "用户管理")
@RequestMapping("${frontPath}/user")
public class UserController extends BaseController {

    WxMaService wxService = WxService.getWxMaService();
    
    @Autowired
	private MemberService memberService;
    
    /**
     * 登陆接口
     */
    @ApiOperation(value = "用户登录(旧)")
    @RequestMapping(value = "login",method = RequestMethod.GET)
    @ApiImplicitParams ({@ApiImplicitParam(name="code",value="code",dataType="String",paramType="query",required =true)
      })
	@ResponseBody
    public String login(String code) {
    	CommonJson result = new CommonJson();
    	log.info("用户微信登录 code="+code);
    	if (StringUtils.isBlank(code)) {
    		result.setMsg("code不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
        }
        try {
            WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code); 
            String openid = session.getOpenid();
            if(StringUtils.isNotBlank(openid)){
	            Member member = memberService.get(openid);
	         	if(member==null){
	         		member = new Member();
	         		member.setId(openid);
	         		member.setCarAmount(0);
	         		member.setSource(1);
	         		member.setStatus(0);
	         		memberService.save(member);//新增用户
	         	}
            }
            log.info(openid);
            result.setData(session.getOpenid());
            log.info("返回微信小程序"+mapper.toJson(result));
            return this.mapper.toJson(result);
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return e.toString();
        }
    }

	/**
	 * 登陆接口2
	 */
	@ApiOperation(value = "用户登录新(返回的是sessionKey，要获得openid请接着调用info2接口)")
	@RequestMapping(value = "login2",method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="code",value="code",dataType="String",paramType="query",required =true)
	})
	@ResponseBody
	public String login2(String code) {
		CommonJson result = new CommonJson();
		log.info("用户微信登录 code="+code);
		if (StringUtils.isBlank(code)) {
			result.setMsg("code不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		try {
			WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
			String openid = session.getOpenid();
			if(StringUtils.isNotBlank(openid)){
				Member member = memberService.get(openid);
				if(member==null){
					member = new Member();
					member.setId(openid);
					member.setCarAmount(0);
					member.setSource(1);
					member.setStatus(0);
					memberService.save(member);//新增用户
				}
			}
			log.info("openid="+openid+"|sessionKey="+session.getSessionKey());
			result.setData(session.getSessionKey());
			log.info("返回微信小程序"+mapper.toJson(result));
			return this.mapper.toJson(result);
		} catch (WxErrorException e) {
			this.logger.error(e.getMessage(), e);
			return e.toString();
		}
	}
    
    
    /**
     * 更新用户用户
     */
    @ApiOperation(value = "用户信息更新")
    @RequestMapping(value = "update",method = RequestMethod.POST)
    @ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
    	@ApiImplicitParam(name="name",value="昵称",dataType="String",paramType="form",required =true),
    	@ApiImplicitParam(name="address",value="地址",dataType="String",paramType="form",required =true)
    })
	@ResponseBody
    public String update(String openid,String name,String address,HttpServletRequest request) {
    	CommonJson result = new CommonJson();
    	log.info("用户信息更新 openid="+openid);
    	if (StringUtils.isBlank(openid)) {
    		result.setMsg("openid不能为空");
			result.setCode(1);
			log.info(mapper.toJson(result));
			return this.mapper.toJson(result);
        }
    	if("undefined".equals(openid)){
    		result.setMsg("openid有误，请核对");
			result.setCode(1);
			log.info(mapper.toJson(result));
			return this.mapper.toJson(result);
    	}
    	if("undefined".equals(address)){
    		result.setMsg("地址有误，请核对");
			result.setCode(1);
			log.info(mapper.toJson(result));
			return this.mapper.toJson(result);
    	}
    	if("undefined".equals(name)){
    		result.setMsg("昵称有误，请核对");
			result.setCode(1);
			log.info(mapper.toJson(result));
			return this.mapper.toJson(result);
    	}
        try {
        	Member member = memberService.get(openid);
        	if(member!=null){
        		if(StringUtils.isNotBlank(name)){
        			member.setName(name);
        		}
        		if(StringUtils.isNotBlank(address)){
        			member.setAddress(address);
        		}
        		member.setIp(request.getRemoteHost());
        		memberService.save(member);//更新用户
        	}
        	result.setData(member);
        	log.info("返回给小程序"+mapper.toJson(result));
            return this.mapper.toJson(result);
        } catch (Exception e) {
        	result.setCode(1);//不存在
    		result.setMsg("查询错误");//不存在
            this.logger.error(e.getMessage(), e);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
    }
    
    /**
     * 获取用户
     */
    @ApiOperation(value = "用户信息获取(旧接口)")
    @RequestMapping(value = "info",method = RequestMethod.GET)
    @ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="query",required =true)
    })
	@ResponseBody
    public String info(String openid) {
    	CommonJson result = new CommonJson();
    	log.info("用户获取用户信息 openid="+openid);
    	if (StringUtils.isBlank(openid)) {
    		result.setMsg("openid不能为空");
			result.setCode(1);
			log.info(mapper.toJson(result));
			return this.mapper.toJson(result);
        }
    	if("undefined".equals(openid)){
    		result.setMsg("openid有误，请核对");
			result.setCode(1);
			log.info(mapper.toJson(result));
			return this.mapper.toJson(result);
    	}
        try {
        	Member member = memberService.get(openid);
        	if(member==null){
        		member = new Member();
        		member.setId(openid);
        		member.setCarAmount(0);
        		member.setSource(1);
        		member.setStatus(0);
        		memberService.save(member);//新增用户
        	}
        	if(member.getCarAmount()==0){//测试阶段
        		member.setCarAmount(1);
        	}
        	result.setData(member);
        	log.info("返回给小程序"+mapper.toJson(result));
            return this.mapper.toJson(result);
        } catch (Exception e) {
        	result.setCode(1);//不存在
    		result.setMsg("查询错误");//不存在
            this.logger.error(e.getMessage(), e);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
    }

	/**
	 * <pre>
	 * 获取用户信息接口
	 * </pre>
	 */

	@ApiOperation(value = "用户信息获取(新接口,后台可自动获取昵称和头像)")
	@RequestMapping(value = "info2",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="sessionKey",value="会话密钥",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="encryptedData",value="消息密文",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="iv",value="加密算法的初始向量",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String info2(String sessionKey,  String encryptedData, String iv) {
		CommonJson result = new CommonJson();
		log.info("用户获取用户信息 sessionKey="+sessionKey+"|encryptedData="+encryptedData+"|iv="+iv);
		// 解密用户信息
		WxMaUserInfo userInfo = this.wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
		if(userInfo==null){
			result.setMsg("小程序获取用户信息失败");
			result.setCode(1);
			log.info(mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		Member member = memberService.get(userInfo.getOpenId());
		if(member==null){
			member = new Member();
			member.setId(userInfo.getOpenId());
			member.setCarAmount(0);
			member.setSource(1);
			member.setStatus(0);

		}
		member.setName(userInfo.getNickName());
		member.setHeadImg(userInfo.getAvatarUrl());//用户头像
		memberService.save(member);//新增用户
		if(member.getCarAmount()==0){//测试阶段
			member.setCarAmount(1);
		}
		result.setData(member);

		log.info(mapper.toJson(result));
		return this.mapper.toJson(result);
	}
}
